import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'

/**
 * 创建 Axios 实例
 */
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
})

/**
 * 请求拦截器
 */
request.interceptors.request.use(config => {
  // 添加请求头 headers
  // config.headers.Authorization = ''
  return config
}, (error) => {
  return Promise.reject(error)
})

/**
 * 响应拦截器
 * response.data:
 *     {
 *         "code": 10000,
 *         "message": "请求成功",
 *         "data": xxx
 *     }
 */
request.interceptors.response.use(response => {
  const { data } = response
  if (data.code === 10000) {
    return data
  }
  ElMessage.error(data.message)
  return Promise.reject(response)
}, error => {
  let message = ''
  let status = error.response.status
  switch (status) {
    case 401:
      message = '无权限访问'
      break
    case 403:
      message = '无权限访问'
      break
    case 404:
      message = '对不起，您访问的资源不存在'
      break
    case 500:
      message = '服务器内部错误'
      break
    default:
      message = '网络异常'
      break
  }
  ElMessage.error(message)
  return Promise.reject(error)
})

export default request
